import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_svg/svg.dart';
import 'package:situation/data/channel/intercom_channel.dart';
import 'package:situation/resources/assets.dart';
import 'package:situation/shared/util/util_permission.dart';
import 'package:situation/widgets/loading/intercom_loading.dart';

class IntercomCall extends StatefulWidget {
  const IntercomCall({super.key});

  @override
  State<IntercomCall> createState() => _IntercomCallState();
}

class _IntercomCallState extends State<IntercomCall> {
  // ================  通信类  ==============
  void onPress(TapDownDetails details) async {
    UtilPermission.requestMicrophonePermission().then((flag) {
      if (!flag) {
        SmartDialog.showToast("请先允许麦克风权限");
        return;
      }
      SmartDialog.showLoading(
        msg: '正在讲话',
        maskColor: Colors.transparent,
        builder: (_) => IntercomLoading(),
      );
      IntercomChannel.to.sendMsg({"event": "speak"});
    });
  }

  void onPressEnd(LongPressEndDetails details) {
    SmartDialog.dismiss();
    IntercomChannel.to.sendMsg({"event": "stopSpeak"});
  }

  void onPressUp(TapUpDetails details) {
    SmartDialog.dismiss();
    IntercomChannel.to.sendMsg({"event": "stopSpeak"});
  }

  void onLongPressDown(LongPressDownDetails details) {
    onPress(TapDownDetails());
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onLongPressDown: onLongPressDown,
      onLongPressEnd: onPressEnd,
      onTapUp: onPressUp,
      child: Center(child: SvgPicture.asset(Assets.svgIntercom, width: 30)),
    );
  }
}
